﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Reflection;

namespace RearLivestock.Beginning.Api.Application.Command.PigWeighings
{
    /// <summary>
    /// 猪只称重显示Handler
    /// </summary>
    public class SearchPigWeighingHandler : IRequestHandler<SearchPigWeighingCommand, Result<PageResultDto<PigWeighingDto>>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 猪只称重
        /// </summary>
        private readonly IBaseRepository<PigsWeighing> pigsWeighingrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPigWeighingHandler> _logger;
        /// <summary>
        /// 猪只基本信息
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationrepository;
        /// <summary>
        /// 品种
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesrepository;
        /// <summary>
        /// 称重类型
        /// </summary>
        private readonly IBaseRepository<WeighingType> weighingTyperepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigsWeighingrepository"></param>
        /// <param name="logger"></param>
        /// <param name="basicInformationrepository"></param>
        /// <param name="varietiesrepository"></param>
        /// <param name="weighingTyperepository"></param>
        public SearchPigWeighingHandler(IMapper mapper, IBaseRepository<PigsWeighing> pigsWeighingrepository, ILogger<SearchPigWeighingHandler> logger, IBaseRepository<BasicInformation> basicInformationrepository, IBaseRepository<Varieties> varietiesrepository, IBaseRepository<WeighingType> weighingTyperepository)
        {
            this.mapper = mapper;
            this.pigsWeighingrepository = pigsWeighingrepository;
            _logger = logger;
            this.basicInformationrepository = basicInformationrepository;
            this.varietiesrepository = varietiesrepository;
            this.weighingTyperepository = weighingTyperepository;
        }
        /// <summary>
        /// 猪只体重
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<PigWeighingDto>>> Handle(SearchPigWeighingCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PigWeighingDto>>() { Code = (int)CommonErrorCode.Search };
            var page = new PageResultDto<PigWeighingDto>() { TotalCount = 0, PageCount = 0, List = new List<PigWeighingDto>() };
            try
            {
                var pigsWeighing = await (from a in await basicInformationrepository.GetAll()
                                          join b in await pigsWeighingrepository.GetAll()
                                          on a.EarNumber equals b.EarNumber
                                          join c in await varietiesrepository.GetAll()
                                          on a.VarietiesId equals c.VarietiesId
                                          join d in await weighingTyperepository.GetAll()
                                          on b.WeighingTypeId equals d.WeighingTypeId
                                          select new PigWeighingDto()
                                          {
                                              PigsWeighingId = b.PigsWeighingId,
                                              WeighingDate = b.WeighingDate,
                                              WeighingTypeId = b.WeighingTypeId,
                                              WeighingName = d.WeighingName,
                                              EarNumber = b.EarNumber,
                                              PigWeight = b.PigWeight,
                                              Gender = a.Gender,
                                              VarietiesId = a.VarietiesId,
                                              VarietiesName = c.VarietiesName
                                          }).ToListAsync();
                //称重日期开始时间
                if (request.SDate != null)
                {
                    pigsWeighing = pigsWeighing.Where(x => x.WeighingDate >= request.SDate).ToList();
                }
                //称重日期结束时间
                if (request.ODate != null)
                {
                    pigsWeighing = pigsWeighing.Where(x => x.WeighingDate <= request.ODate).ToList();
                }
                //耳号模糊查
                if (!string.IsNullOrEmpty(request.EarNumber))
                {
                    pigsWeighing = pigsWeighing.Where(x => x.EarNumber.Contains(request.EarNumber)).ToList();
                }
                //称重类型ID查询
                if (request.WeighingTypeId>0)
                {
                    pigsWeighing= pigsWeighing.Where(x=>x.WeighingTypeId==request.WeighingTypeId).ToList();
                }
                //品种ID查询
                if (request.VarietiesId > 0)
                {
                    pigsWeighing = pigsWeighing.Where(x => x.VarietiesId == request.VarietiesId).ToList();
                }
                //性别ID查询
                if (request.Gender !=null)
                {
                    pigsWeighing = pigsWeighing.Where(x => x.Gender==request.Gender).ToList();
                }

                page.TotalCount = pigsWeighing.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                page.List = pigsWeighing.OrderBy(x => x.PigsWeighingId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = page;
                result.Msg = "猪只称重显示成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("猪只称重显示失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
